class Swiper {
  el = null
  //页面数字元素
  numsItems = []
  //每一个块元素
  sections = []
  constructor(options) {
    this.options = options
  }
  run() {
    this.createEl()
    this.creaeNums()

    this.addNumEvent()
  }
  //点击数字编号进行轮换
  addNumEvent() {
    this.numsItems.map((item, i) => {
      item.addEventListener('click', () => {
        this.removeNumClickClass()
        item.classList.add('active')
        this.sections.map((section, index) => {
          setTimeout(() => {
            section.style.transform = `rotateX(${i * 90}deg)`
          }, index * this.options.timeout)
        })
      })
    })
  }
  removeNumClickClass() {
    this.numsItems.map((item, i) => item.classList.remove('active'))
  }

  //创建页面数字编号
  creaeNums() {
    const div = document.createElement('div')
    div.classList.add('paginate')
    for (const n of [1, 2, 3, 4]) {
      let span = document.createElement('span')
      span.innerText = n
      div.insertAdjacentElement('beforeEnd', span)
      this.numsItems.push(span)
    }
    this.el.insertAdjacentElement('beforeEnd', div)
  }
  //创建主元素
  createEl() {
    this.el = document.querySelector(this.options.el)
    this.el.style.width = this.options.width + 'px'
    this.el.style.height = this.options.height + 'px'

    const container = document.createElement('div')
    container.classList.add('container')
    container.style.width = this.options.width + 'px'
    container.style.height = this.options.height + 'px'

    for (let i = 0; i < this.options.limit; i++) {
      container.insertAdjacentElement('beforeEnd', this.createSection(i))
    }
    this.el.insertAdjacentElement('beforeEnd', container)
  }
  //创建分块的DIV元素
  createSection(index) {
    let section = document.createElement('section')
    section.style.width = this.width() + 'px'
    section.style.height = this.options.height + 'px'
    section.style.transformOrigin = `center center -${this.options.height / 2}px`
    this.sections.push(section)

    for (const [, path] of this.options.images.entries()) {
      let div = document.createElement('div')
      div.style.width = `${this.width()}px`
      div.style.height = `${this.options.height}px`
      div.style.transformOrigin = `center center -${this.options.height / 2}px`

      let img = document.createElement('img')
      img.src = path
      img.style.cssText = `transform: translateX(-${this.width() * index}px)`

      div.insertAdjacentElement('beforeEnd', img)
      section.insertAdjacentElement('beforeEnd', div)
    }
    return section
  }
  //获取每个小块的宽度
  width() {
    return this.options.width / this.options.limit
  }
}
